<template>
  <div class="_wz_MaterialAdd">
    <Form ref="formAdd" :model="formData" label-position="right" :label-width="80" :rules="ruleValidate">

      <FormItem label="运输企业" prop="deptUuid">
        <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable>
          <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
        </i-select>
      </FormItem>
      <FormItem label="课件名称" prop="materialTrainName">
        <i-input v-model="formData.materialTrainName" placeholder="请填写课件名称" clearable />
      </FormItem>
      <Row>
        <i-col span="12">
          <FormItem label="课件时长" prop="materialTrainDuration">
            <i-input v-model.number="formData.materialTrainDuration" placeholder="请填写课件时长" clearable />
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="推荐时长">
            {{tjsc}}
          </FormItem>
        </i-col>
      </Row>
      <FormItem label="课件方向" prop="materialTrainDirection">
        <i-select v-model="formData.materialTrainDirection" filterable placeholder="请选择课件方向" @on-change="public.selectName($event,formData,'materialTrainDirectionName')" :label-in-value="true" clearable>
          <Option v-for="item in optionsData" :value="item.code" :key="item.code">{{ item.value }}</Option>
        </i-select>
      </FormItem>
      <FormItem label="课件上传" class="ivu-form-item-required">
        <div>
          <Upload name="multipartFile" :before-upload="handleUpload" action="">
            <Button type="primary" icon="ios-cloud-upload-outline">请选择上传课件文件</Button>
            {{fileName}}
          </Upload>
        </div>
      </FormItem>
      <FormItem label="课件类型" prop="materialTrainType" v-show="false">
        <RadioGroup v-model="formData.materialTrainType" @on-change="changeRadio">
          <Radio :label="1" key="1">视频课件</Radio>
          <Radio :label="2" key="2">文档课件</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="注意事项">
        （一）上传课件大小不可超过600MB<br />
        （二）文件型课件只支持2007版文件（docx）和mp4格式的视频<br />
        （三）课件时长不能低于10分钟<br />
        <span style="color: #ed4014;">（四）添加后，会自动上传至审核，如驳回后再次修改，会自动上传至审核。已经审核通过不可修改、删除。</span>
      </FormItem>

    </Form>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
      <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
    </div>
  </div>
</template>
<script>
  import {Spin} from "view-design";

  export default {
    //modify 修改 add 新增
    // 需要修改的数据  表单类型  打开方式
    props: ["selectData"],//接收来自父组件的数据
    data() {
      return {
        uploadProgress: 0,

        subDeptList :[],//下级企业

        fileType: null,//文件类型
        file: null,//文件
        fileName: "",//上传前 获取本地的文件名称
        tjsc: "根据上传课件，推荐学习时长",//推荐时长
        formData: {},//表单数据
        optionsData: [],//下拉加载
        ruleValidate: {//正则
          deptUuid: [
            {required: true, message: '请选择运输企业', trigger: 'blur'}
          ],
          materialTrainName: [
            {required: true, message: '课件名称不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                value.length <= 20 ? callBack() : callBack('课件名称最多可填写20个字符')
              }, trigger: 'blur'
            }
          ],
          materialTrainDuration: [
            {required: true, message: '请填写学习时长（单位：分钟）'},
            {type: 'number', message: '必须为数字值'},
            {
              validator: (rule, value, callBack) => {
                value >= 10 ? callBack() : callBack('课件时长不能低于10分钟')
              }, trigger: 'blur'
            }
          ],
          materialTrainDirection: [
            {required: true, message: '请选择课件方向', trigger: 'blur'}
          ],
        }
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态
    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      let that = this;



      //加载方向
      that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'training_direction'}).then(res => {
        if (!!res) {
          that.optionsData = res.data.data
        }
      }).catch(err => {
        console.log('失败', err);
      })

      if (!!that.selectData.id) {//修改
        that.formData = that.selectData;//表单
        delete that.formData.createTime;

      } else {
        that.formData = {
          materialTrainType: 1,
          materialTrainOpen: 0
        };//表单
      }


      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList,{}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          if(!!that.selectData.id){
            that.formData.deptUuid = res.data.data[0].uuid;
          }
        }
      }).catch(err => {
        console.log("失败", err)
      })


    },
    methods: {//执行的方法
      //提交表单
      addSubmit(data) {
        let that = this;
        that.$refs[data].validate((valid) => {
          if (valid) {//正则判断使用
            let data = that.formData;
            let formData = new FormData();

            for (let key in data) {
              if (!!data[key] && data[key] != 'null') {
                formData.append(key, data[key]);
              }
            }


            //后台说不管修改还是添加都要天加文件
            if (!!!that.file) {
              if (!!!that.selectData.id) {
                that.$Message.error('请上传课件素材');
                return false;
              }
            } else {
              formData.append('multipartFile', that.fileData);
              //切片使用
              // var bytesPerPiece = 1024 * 1; // 每个文件切片大小定为1MB .
              // var totalPieces;
              // var blob = that.fileData;
              // var start = 0;
              // var end;
              // var index = 0;
              // var filesize = blob.size;
              // //计算文件切片总数
              // totalPieces = Math.ceil(filesize / bytesPerPiece);
              // while(start < filesize) {
              //   end = start + bytesPerPiece;
              //   if(end > filesize) {
              //     end = filesize;
              //   }
              //   var chunk = blob.slice(start,end);//切割文件
              //   formData.append("multipartFile", chunk);
              //
              //   start = end;
              //   index++;
              // }
            }

            that.axios.post(that.apiUrl.webApi + "/educate/materialTrain/materialTrainSaveOrUpdate", formData, that.public.parameterUploadProgress(that)).then(res => {
              that.$Spin.hide();
              if (!!res) {
                that.$Message.success("保存成功");
                that.$emit("closeFun", true)

                // 提交后转码
                //that.axios.post(that.apiUrl.webApi + "/educate/materialTrain/materialTrainConversion", {materialUuid: res.data.data})
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {
            that.$Message.error('请正确填写表单');
          }
        })
      },
      //选择文件
      handleUpload(file) {
        let that = this;
        // file.size 字节

        //1024 * 1; // 每个文件切片大小定为600MB
        if (file.size > 1 * 1024 * 1024 * 600) {
          that.$Message.error('您上传的文件超过600MB.');
          return false;
        }

        //判断文件类型
        let type = file.name.substr((file.name.lastIndexOf(".") + 1));
        if (type == "MP4" || type == "OGG" || type == "WEBM" || type == "mp4" || type == "ogg" || type == "webm") {//视频
          that.formData.materialTrainType = 1;
          that.fileType = "1";
          let url = URL.createObjectURL(file);
          let audioElement = new Audio(url);
          audioElement.addEventListener("loadedmetadata", function (_event) {
            let duration = parseInt(audioElement.duration / 60) + 1;
            that.tjsc = ((duration < 1) ? 1 : duration) + "分钟"; //时长为秒，小数，182.36
          });
          that.fileData = file;
        } else if (type == "DOCX" || type == "docx") {//word
          that.formData.materialTrainType = 2;
          that.fileType = "2";
          that.tjsc = "根据上传课件，推荐学习时长";
          that.fileData = file;
        } else {
          that.$Message.error('您上传的文件类型不匹配');
          return false;
        }
        that.file = file;
        that.fileName = file.name;
        return false;
      },
      //监听文件类型单选
      changeRadio(data) {
        let that = this;
        if (!!that.file) {//有文件
          if (data != that.fileType) {
            that.$Message.error("您选择的文件类型和您上传的文件不匹配")
            that.$nextTick(function () {//监听页面渲染完成
              that.formData.materialTrainType = that.fileType;
            })
          }
        } else {
          that.formData.materialTrainType = data;
        }
      },
    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less">
  ._wz_MaterialAdd {

  }
</style>
